package com.wondersgroup.fjzlpt.org.service.impl.xymb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.quick.framework.boot.repository.nosql.mongodb.inter.IMongoOperator;
import com.quick.framework.exception.ServiceException;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.LoggerUtil;
import com.wondersgroup.fjzlpt.org.dao.inter.fwxx.FwxxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.QysjbDao;
import com.wondersgroup.fjzlpt.org.dao.inter.xymb.XyfwxxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.xymb.XymbDAO;
import com.wondersgroup.fjzlpt.org.service.inter.xymb.XymbService;

import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by lion on 2017/7/3.
 */
@Service
public class XymbServiceImpl implements XymbService {


    @Autowired
    private FwxxDAO fwxxDAO;
    @Autowired
    private XymbDAO xymbDAO;
    @Autowired
    private XyfwxxDAO xyfwxxDAO;
    @Autowired
    private QysjbDao qysjbDao;
    @Autowired
    private IMongoOperator mongoOperator;

    private static final String xymb_tableName = "XYMB";

    /**
     * 分页查询协议模板
     * @return
     */
    public JSONObject queryPageXymb(Map<String, String> map){
        return xymbDAO.queryPageXymb(map);
    }

    /**
     * 获取协议模板内容
     * @return
     */
    public JSONObject queryXymb(String XYMBID){
        JSONObject jsonObject = new JSONObject(1);
        try {
            /*查询mongo存储的模板内容*/
            jsonObject = mongoOperator.executeQuery(xymb_tableName, QueryBuilder.start("_id").is(new ObjectId(XYMBID)), "CONTENT").getJSONObject(0);
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000901","获取协议出错，请稍后再试！");
        }
        return jsonObject;
    }

    /**
     * 保存协议模板
     * @param map
     * @return
     */
    public JSONObject save(Map map){
        String xyCONTENT = map.get("CONTENT").toString().replaceAll("gzbBfh","%")
                .replaceAll("gzbJh","+");
        map.put("CONTENT",xyCONTENT);
        ResultObject ro = new ResultObject();
        try{
            String XYMBID = (String)map.get("XYMBID");
            if(StringUtils.isEmpty(XYMBID)){
                add(map);
            }else{
                update(map);
            }
        }
        catch (Exception e){
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000902","新增协议模板失败");
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    private void add(Map map) throws Exception {
        String CONTENT = (String)map.remove("CONTENT");
        JSONObject json = new JSONObject(1);
        json.put("CONTENT", CONTENT);
        DBObject dbo = (DBObject)com.mongodb.util.JSON.parse(json.toString());
        /*保存协议页面*/
        String XYMBID = mongoOperator.executeInsertOne(xymb_tableName, dbo);
        /*添加协议创建日期*/
        map.put("CJRQ", new Date());
        map.put("XYMBID", XYMBID);

        if("01".equals(map.get("XYMBLX")) && "1".equals(map.get("ZT"))) {
            xymbDAO.updateJtqyxyZt(null);
        }else if("02".equals(map.get("XYMBLX"))){
            /*添加协议服务*/
            insertXyfw(map);
        }
        xymbDAO.insert(map);
    }

    private void update(Map map) throws Exception {
        String XYMBID = (String)map.get("XYMBID");
        JSONObject json = new JSONObject(1);
        String CONTENT = (String)map.remove("CONTENT");
        json.put("CONTENT", CONTENT);
        DBObject dbo = (DBObject)com.mongodb.util.JSON.parse(json.toString());
        /*更新协议页面*/
        this.mongoOperator.executeUpdate(this.xymb_tableName, QueryBuilder.start("_id").is(new ObjectId(XYMBID)), dbo);

        if("01".equals(map.get("XYMBLX")) && "1".equals(map.get("ZT"))) {
            xymbDAO.updateJtqyxyZt(null);
        }else if("02".equals(map.get("XYMBLX"))){
            /*删除协议服务*/
            this.xyfwxxDAO.deleteByXYMBID(XYMBID);
            /*添加协议服务*/
            insertXyfw(map);
        }
        this.xymbDAO.updateForPrimaryKey(map);
    }

    private void insertXyfw(Map map){
        String XYMBID = (String)map.get("XYMBID");
        /*服务IDs*/
        String FWIDS = (String)map.remove("FWIDS");
        if(!StringUtils.isEmpty(FWIDS)){
            List<Map> list = new ArrayList<Map>();
            String[] ids = FWIDS.split(",");
            for(int i = 0; i < ids.length ; i ++ )
            {
                Map xyfwMap = new HashMap<>();
                xyfwMap.put("XYMBID", XYMBID);
                xyfwMap.put("FWID", ids[i]);
                list.add(xyfwMap);
            }
            this.xyfwxxDAO.insertBatch(list);
        }
    }

    /**
     * 查询服务项概要信息
     * @return
     */
    public JSONObject queryPageSummaryFwxx(Map<String, String> map){
        try{
            return fwxxDAO.queryPageSummaryFwxx(map);
        }catch (Exception e){
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000903","查询服务项概要信息失败");
        }
    }
    
    /**
     * 保存协议并返回协议id
     * @param map
     * @return
     */
    public JSONObject saveXyAndResutXyid(Map<String, String> map){
    	String CONTENT = (String)map.remove("CONTENT");
        JSONObject json = new JSONObject(1);
		try {
			json.put("CONTENT", CONTENT);
			DBObject dbo = (DBObject)com.mongodb.util.JSON.parse(json.toString());
			/*保存协议页面*/
			String XYMBID = mongoOperator.executeInsertOne(xymb_tableName, dbo);
			json.clear();

			/*保存协议服务  */
			map.put("XYMBID", XYMBID);
			this.insertXyfw(map);
			
			json.put("XYMBID", XYMBID);
			json.put("state", "true");
		} catch (Exception e) {
			json.put("info", "协议保存失败！");
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000904","协议保存失败！");
		}
        return json;
    }

    @Override
    public JSONObject getJtqyXymb() {
        JSONObject result = xymbDAO.queryJtqyXymbDefault();
        return queryXymb(result.getString("XYMBID"));
    }
    /**
     * 查询正在使用中的家庭签约协议模板
     * @return
     */
    public JSONObject queryUseJtqyxy(Map<String,String> map){
        ResultObject ro = new ResultObject();

        //查询启用中家签协议模板
        Map<String, String> map1 = new HashMap<>();
        map1.put("XYMBLX","01");
        map1.put("ZT","1");
        JSONObject xyObj = xymbDAO.queryOne(map1);

        if(xyObj.isEmpty()){
            ro.changeFaultState("无启用中的家庭签约协议,请联系系统管理员进行启用!");
        }else{
            String XYMBID = xyObj.getString("XYMBID");
            JSONObject xymbObj = this.queryXymb(XYMBID);
            ro.setInfo((Map)xymbObj);

            /** 获取协议号 */
            String XYH = qysjbDao.queryMaxXyh(map.get("JGXZQHDM"));
            ro.setInfo("XYH", XYH);
        }
        return (JSONObject)JSON.toJSON(ro);
    }
}
